<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/2/21
 * Time: 15:14
 */
declare(strict_types=1);

namespace App\Service;
use App\Model\Dao\MchAccountAccessDao;
use App\Model\Dao\MchAccountAccessDetailDao;
use App\Model\Dao\MchAccountDao;
use App\Model\Dao\RateSettleDao;
use App\Model\Dao\TradeTransDao;
use App\Utils\CustomUtils;
use Exception;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

/**
 * Class SettleWithdrawService
 * @package App\Service
 * 商户提现、转账到银行卡结算
 */
class SettleWithdrawService extends CommonService
{

    /**
     * @Inject()
     * @var TradeTransDao
     */
    private $TradeTransDao;

    /**
     * @Inject()
     * @var MchAccountDao
     */
    private $MchAccountDao;

    /**
     * @Inject()
     * @var MchAccountAccessDao
     */
    private $MchAccountAccessDao;

    /**
     * @Inject()
     * @var MchAccountAccessDetailDao
     */
    private $MchAccountAccessDetailDao;

    /**
     * @Inject()
     * @var RateSettleDao
     */
    private $RateSettleDao;

    public function handle($param) {
        // 校验
        $withdraw = $this->TradeTransDao->get($param['withdrawId']);
        if(!$withdraw || $withdraw['type'] == 2) {
            throw new Exception('提现不存在，终止处理', FAILED_CODE);
        }
        if($withdraw['handleStatus'] != $param['handleStatus']) {
            throw new Exception('提现单处理状态不对应', FAILED_CODE);
        }
        if($withdraw['settleStatus'] == 1) {
            throw new Exception('提现单结算完成', FAILED_CODE);
        }
        $mchAccount = $this->MchAccountDao->get($param['mchAccountId']);
        if(!$mchAccount) {
            throw new Exception('查询账户记录失败', FAILED_CODE);
        }
        $isDetail = $this->MchAccountAccessDetailDao->getWhere([
            "withdrawId"    => $withdraw['id'],
            "type"          => TYPE_WITHDRAW_CASH_OUT,
        ]);

        if ($param['handleStatus'] == 0) {
            if ($isDetail && empty($isDetail['accessId'])) {
                throw new Exception('提现单已冻结结算', FAILED_CODE);
            }
            return $this->handleAdd($param, $withdraw, $mchAccount);
        } else {

            // 初审通过不用管
            if ($param['handleStatus'] == 1) {
                return $this->handleFirstConfirm($withdraw);
            }
            return $this->handleConfirm($param, $withdraw, $mchAccount);
        }
    }

    private function handleFirstConfirm($withdraw) {
        $this->TradeTransDao->set($withdraw['id'], [
            'settleStatus'  => 1,
        ]);
        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "提现单初审通过结算成功");
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 新增提现记录，出入账
     */
    public function handleAdd($param, $withdraw, $mchAccount) {

        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transAmount = $withdraw['transAmount'];

        // 交易可提现金额 余额前后
        $beforeTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterTradeCashAmount  = $mchAccount['tradeCashAmount'] - $transAmount;

        // 事件待审核冻结金额 余额前后
        $beforeEventReviewFrozenAmount = $mchAccount['eventReviewFrozenAmount'];
        $afterEventReviewFrozenAmount = $mchAccount['eventReviewFrozenAmount'] + $transAmount;

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.可提现出账
            // 2.可提现入账
            // 3.更新提现单状态
            // 4.更新账户
            $this->handleCashOutTransAmount($param, $withdraw, $mchAccount, $transAmount, $beforeTradeCashAmount, $afterTradeCashAmount);

            $this->handleFrozenInTransAmount($param, $withdraw, $mchAccount, $transAmount, $beforeEventReviewFrozenAmount, $afterEventReviewFrozenAmount);

            $this->TradeTransDao->set($withdraw['id'], [
                'settleStatus'  => 1,
            ]);

            $updateMchAccount = array(
                "tradeCashAmount"           => $afterTradeCashAmount,
                "eventReviewFrozenAmount"   => $afterEventReviewFrozenAmount,
                "updateVersion"             => $updateVersion
            );
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "提现单结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "提现单结算成功");
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，提现金额，可提现出账
     */
    private function handleCashOutTransAmount($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_WITHDRAW_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $withdraw['transCurrency'],
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "remark"            => "提现单可提现账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，提现金额，冻结金额入账
     */
    private function handleFrozenInTransAmount($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_EVENT_REVIEW,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_WITHDRAW_FROZEN_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $withdraw['transCurrency'],
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "remark"            => "提现单冻结账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 提现，审核，出入账
     */
    private function handleConfirm($param, $withdraw, $mchAccount) {
        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transAmount = $withdraw['transAmount'];

        // 交易可提现金额，提现金额，余额前后
        $beforeTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterTradeCashAmount  = $mchAccount['tradeCashAmount'] + $transAmount;

        // 事件审核冻结金额，提现金额，余额前后
        $beforeEventReviewFrozenAmount = $mchAccount['eventReviewFrozenAmount'];
        $afterEventReviewFrozenAmount = $mchAccount['eventReviewFrozenAmount'] - $transAmount;

        // 交易可提现金额出账，提现金额，余额前后
        $beforeOutTradeCashAmount = $afterTradeCashAmount;
        $afterOutTradeCashAmount  = $afterTradeCashAmount - $transAmount;

        // 交易可提现金额，扣转账手续费，余额前后
        $withdrawPerFee = 0;
        $beforeWithdrawPerFeeTradeCashAmount = 0;
        $afterWithdrawPerFeeTradeCashAmount  = 0;
        if ($param['handleStatus'] == 3) {
            $rateSettle = $this->RateSettleDao->getByMchId($withdraw['mchId']);
            if(!$rateSettle) {
                throw new Exception('查询商户结算费率失败', FAILED_CODE);
            }
            $withdrawPerFee = $rateSettle['withdrawPerFee'];
            $beforeWithdrawPerFeeTradeCashAmount = $afterOutTradeCashAmount;
            $afterWithdrawPerFeeTradeCashAmount = $beforeWithdrawPerFeeTradeCashAmount - $withdrawPerFee;
        }

        // 提现总金额
        $tradeWithdrawAmount  = $mchAccount['tradeWithdrawAmount'] + $transAmount;

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.提现冻结账户出账
            // 2.提现可提现账户入账
            // 3.审核成功，可提现账户出账
            // 4.审核成功，可提现账户手续费出账
            // 5.更新提现结算状态
            // 6.更新账户

            // step 1
            $accessId = $this->handleConfirmFrozenOutTransAmount($param, $withdraw, $mchAccount, $transAmount, $beforeEventReviewFrozenAmount, $afterEventReviewFrozenAmount);

            // handleAdd新增时添加的记录，查询
            $frozenInDetail = $this->MchAccountAccessDetailDao->getWhere(['withdrawId'  => $withdraw['id'], 'type' => TYPE_WITHDRAW_FROZEN_IN]);

            $this->MchAccountAccessDetailDao->update($frozenInDetail['id'], ['accessId' => $accessId]);

            // step 2
            $confirmCashInId = $this->handleConfirmCashInTransAmount($param, $withdraw, $mchAccount, $transAmount, $beforeTradeCashAmount, $afterTradeCashAmount);

            if ($param['handleStatus'] == 3) {
                // step 3
                $accessId = $this->handleConfirmCashOutTransAmount($param, $withdraw, $mchAccount, $transAmount, $beforeOutTradeCashAmount, $afterOutTradeCashAmount);

                $this->MchAccountAccessDetailDao->update($confirmCashInId, ['accessId' => $accessId]);

                // handleAdd新增时添加的记录，查询
                $cashOutDetail = $this->MchAccountAccessDetailDao->getWhere(['withdrawId'  => $withdraw['id'], 'type' => TYPE_WITHDRAW_CASH_OUT]);

                $this->MchAccountAccessDetailDao->update($cashOutDetail['id'], ['accessId' => $accessId]);

                // step 4
                $this->handleConfirmWithdrawPerFee($param, $withdraw, $mchAccount, $withdrawPerFee, $beforeWithdrawPerFeeTradeCashAmount, $afterWithdrawPerFeeTradeCashAmount);
            }

            // 审核成功
            if ($param['handleStatus'] == 3) {
                // step 5
                $this->TradeTransDao->set($withdraw['id'], [
                    'settleStatus'  => 1,
                    'settleTime'    => time(),
                    'transFee'      => $withdrawPerFee
                ]);

                // step 6
                $updateMchAccount = array(
                    "tradeCashAmount"           => $afterWithdrawPerFeeTradeCashAmount,
                    "eventReviewFrozenAmount"   => $afterEventReviewFrozenAmount,
                    "tradeWithdrawAmount"       => $tradeWithdrawAmount,
                    "updateVersion"             => $updateVersion
                );
            } else {
                // step 5
                $this->TradeTransDao->set($withdraw['id'], [
                    'settleStatus'  => 1,
                    'settleTime'    => time()
                ]);

                // step 6
                $updateMchAccount = array(
                    "tradeCashAmount"           => $afterTradeCashAmount,
                    "eventReviewFrozenAmount"   => $afterEventReviewFrozenAmount,
                    "updateVersion"             => $updateVersion
                );
            }
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易提现审核结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易提现审核结算成功");
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，提现金额，可提现入账
     */
    private function handleConfirmCashInTransAmount($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_WITHDRAW_CONFIRM_CASH_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $withdraw['transCurrency'],
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "remark"            => "提现单可提现账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccessDetail['id'];
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，提现金额，可提现出账，提现成功
     */
    private function handleConfirmCashOutTransAmount($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $withdraw["mchId"],
            "mchNo"        => $withdraw["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_WITHDRAW,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "withdrawId"   => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "amount"       => -$amount,
            "currency"     => $withdraw['transCurrency'],
            "status"       => 1,
            "remark"       => "提现单提现",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_WITHDRAW_CONFIRM_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $withdraw['transCurrency'],
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "remark"            => "提现单提现",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 确认，提现金额，解冻账户出账
     */
    private function handleConfirmFrozenOutTransAmount($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $withdraw["mchId"],
            "mchNo"        => $withdraw["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_WITHDRAW,
            "accountType"  => ACCOUNT_TYPE_EVENT_REVIEW,
            "withdrawId"   => $withdraw['id'],
            "withdrawNo"   => $withdraw['transNo'],
            "amount"       => 0,
            "currency"     => $withdraw['transCurrency'],
            "status"       => 1,
            "isShow"       => 0,
            "remark"       => "提现单解冻",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_EVENT_REVIEW,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_WITHDRAW_CONFIRM_FROZEN_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $withdraw['transCurrency'],
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "remark"            => "提现单事件审核冻结账户解冻出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $withdraw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提现手续费出账
     */
    private function handleConfirmWithdrawPerFee($param, $withdraw, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $withdraw["mchId"],
            "mchNo"        => $withdraw["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_WITHDRAW,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "withdrawId"   => $withdraw['id'],
            "withdrawNo"   => $withdraw['transNo'],
            "amount"       => -$amount,
            "currency"     => $withdraw['transCurrency'],
            "status"       => 1,
            "remark"       => "提现单手续费费出账",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $withdraw["mchId"],
            "mchNo"             => $withdraw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_WITHDRAW_CONFIRM_WITHDRAW_PER_FEE_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "withdrawId"        => $withdraw['id'],
            "withdrawNo"        => $withdraw['transNo'],
            "currency"          => $withdraw['transCurrency'],
            "remark"            => "提现单手续费费出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }
}